<template>
  <div id="driverDetail" class="list">
    <div class="breadcrumb">
			<Breadcrumb separator=">">
				<BreadcrumbItem to="">司机视图</BreadcrumbItem>
				<BreadcrumbItem to="/driver/view">司机视图</BreadcrumbItem>
				<BreadcrumbItem to="/driver/view/detail">司机详情</BreadcrumbItem>
			</Breadcrumb>
			<div class="btns">
				<ButtonGroup>
	        <Button type="text" @click="toSta"><span>更多历史数据</span> <i class="fa fa-angle-double-right"></i></Button>
	    	</ButtonGroup>
			</div>
		</div>
    <TableSearch>
      <Form :label-width="80">
        <Row :gutter="16">
          <Col :md="8">
            <FormItem label="司机">
              <DriverComplete v-model="driverId" ref="driverComplete"></DriverComplete>
            </FormItem>
          </Col>
        </Row>
      </Form>
			<Button type="primary" class="search-btn" icon="search" @click="search" long>查询</Button>
		</TableSearch>

    <div class="main">
      <Row :gutter="16">
        <Col :md="18" class="main-left">
          <Row :gutter="16">
            <Col :md="6" class="chart-col">
              <div class="block">
                <div class="block-body">
                  <div class="dash-board-box">
                    <div id="dashBoardChart" style="width:100%;height:240px;"></div>
                    <div class="dash-board-foot">
                      <div class="rank">
                        <span>车队 内排名</span>
                        <span class="rank-num">{{data.teamRanking|isNull}}</span>
                      </div>
                      <div class="info">
                        <span>公司排名 {{data.companyRanking|isNull}}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </Col>
            <Col :md="18">
              <Card dis-hover>
                <div class="info-grid">
                  <div class="grid-item">
                    <Row>
                      <Col :md="5" :offset="2">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{((data.mileage||0)/1000).toFixed(0)}}</span>
                            <span class="unit">公里</span>
                          </div>
                          <div class="data-name">行驶里程累计</div>
                        </div>
                      </Col>
                      <Col :md="5">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{durationHours}}</span>
                            <span class="unit">小时</span>
                          </div>
                          <div class="data-name">行驶时长累计</div>
                        </div>
                      </Col>
                      <Col :md="5">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.totalWzTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">违章累计</div>
                        </div>
                      </Col>
                      <Col :md="5">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.accidentTtimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">事故累计</div>
                        </div>
                      </Col>
                    </Row>
                  </div>
                  <div class="grid-item">
                    <Row>
                      <Col :md="4" :offset="2">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.overspeedTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">超速累计</div>
                        </div>
                      </Col>
                      <Col :md="4">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.fatigueDrivingTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">疲劳驾驶累计</div>
                        </div>
                      </Col>
                      <Col :md="4">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.accelerateTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">急加速累计</div>
                        </div>
                      </Col>
                      <Col :md="4">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.decelerateTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">急减速累计</div>
                        </div>
                      </Col>
                      <Col :md="4">
                        <div class="data-box">
                          <div class="data-number">
                            <span>{{data.sharpTurnTimes|isNull}}</span>
                            <span class="unit">次</span>
                          </div>
                          <div class="data-name">急转弯累计</div>
                        </div>
                      </Col>
                    </Row>
                  </div>
                </div>
              </Card>
              <div class="search-box">
                <Button :class="{'ivu-btn-primary':twelveMonthActive}" @click="twelveMonthClick">最近12个月</Button>
                <DatePicker v-model="searchYear" type="year" :options="yearOption" :editable="false" :clearable="false" placement="bottom-end" transfer placeholder="选择年" style="width:120px;"></DatePicker>
              </div>
            </Col>
          </Row>
          <Row :gutter="16" style="margin-top:15px;">
            <Col :md="24">
              <Card dis-hover>
                <div slot="title">行驶里程/时长</div>
                <div id="driveChart" style="width:100%;height:220px;"></div>
              </Card>
            </Col>
          </Row>
        </Col>
        <Col :md="6" class="main-right">
          <Card dis-hover>
            <div slot="title">
              <div class="driver-media">
                <div class="pic">
                  <img v-if="data.headPicUrl" :src="data.headPicUrl" />
                  <Icon v-else type="person" size="210"></Icon>
                </div>
                <div class="name">
                  <span>{{data.driverName}}</span>
                  <span>（ {{['男','女'][data.sex]}} {{data.age|isNull}}岁 ）</span>
                </div>
                <div class="more">
                  <a @click="showImage(data.drivingLicencePicUrl)">查看驾驶证</a>
                </div>
              </div>
            </div>
            <div class="driver-info">
              <div class="info-item">
                <label>工号：</label>
                <span>{{data.jobNumber|isNull}}</span>
              </div>
              <div class="info-item">
                <label>驾龄：</label>
                <span>{{data.driveAge|isNull}}</span>
              </div>
              <div class="info-item">
                <label>手机号：</label>
                <span>{{data.tel|isNull}}</span>
              </div>
              <div class="info-item">
                <label>身份证：</label>
                <span>{{data.idNumber|isNull}}</span>
              </div>
              <div class="info-item">
                <label>紧急联系人：</label>
                <span>{{data.emergencyContact|isNull}}</span>
              </div>
              <div class="info-item">
                <label>默认车辆：</label>
                <span>{{data.plateNumber|isNull}}</span>
                <a @click="showImage(data.vehicleLicensePicUrl)">查看行驶证</a>
              </div>
              <div class="info-item">
                <label>所属车队：</label>
                <span>{{data.orgName|isNull}}</span>
              </div>
            </div>
          </Card>
        </Col>
      </Row>
      <Row :gutter="16" style="margin-top:15px;">
        <Col :md="18" class="main-left">
          <Card dis-hover>
            <div slot="title">不良驾驶行为</div>
            <div id="driveBehaviorChart" style="width:100%;height:220px;"></div>
          </Card>
        </Col>
        <Col :md="6" class="main-right">
          <Card dis-hover>
            <div slot="title">百公里均值</div>
            <div class="list-info">
              <div class="list-item">
                <div class="item-name">超速</div>
                <div class="item-number"><span class="number">{{data.bglOverspeedTimes|isNull}}</span><span class="unit">次</span></div>
              </div>
              <div class="list-item">
                <div class="item-name">疲劳驾驶</div>
                <div class="item-number"><span class="number">{{data.bglFatigueDrivingTimes|isNull}}</span><span class="unit">次</span></div>
              </div>
              <div class="list-item">
                <div class="item-name">急加速</div>
                <div class="item-number"><span class="number">{{data.bglAccelerateTimes|isNull}}</span><span class="unit">次</span></div>
              </div>
              <div class="list-item">
                <div class="item-name">急减速</div>
                <div class="item-number"><span class="number">{{data.bglDecelerateTimes|isNull}}</span><span class="unit">次</span></div>
              </div>
              <div class="list-item">
                <div class="item-name">急转弯</div>
                <div class="item-number"><span class="number">{{data.bglSharpTurnTimes|isNull}}</span><span class="unit">次</span></div>
              </div>
            </div>
          </Card>
        </Col>
      </Row>
      <Row :gutter="16" style="margin-top:15px;">
        <Col :md="18" class="main-left">
          <Card dis-hover>
            <div slot="title">不良操作行为</div>
            <div id="operBehaviorChart" style="width:100%;height:220px;"></div>
          </Card>
        </Col>
        <Col :md="6" class="main-right">
          <Card dis-hover>
            <div slot="title">百公里均值</div>
            <div class="list-info">
              <div class="list-item">
                <div class="item-name">行驶中拨打电话</div>
                <div class="item-number"><span class="number">{{data.callPhoneTimes|isNull}}</span><span class="unit">次</span></div>
              </div>
              <div class="list-item">
                <div class="item-name">行驶中看手机</div>
                <div class="item-number"><span class="number">{{data.lookPhoneTimes|isNull}}</span><span class="unit">次</span></div>
              </div>
            </div>
          </Card>
        </Col>
      </Row>
      <Card dis-hover style="margin-top:15px;">
        <div slot="title">情绪</div>
        <Row :gutter="32">
          <Col :md="18">
            <div id="moodChart" style="width:100%;height:220px;"></div>
          </Col>
          <Col :md="6">
            <div id="moodCalendarChart" style="width:100%;height:220px;"></div>
          </Col>
        </Row>
      </Card>
      <Card dis-hover style="margin-top:15px;">
        <div slot="title">生活习惯</div>
        <div slot="extra" class="habits-desc">
          <span>过度(睡眠大于8小时)</span>
          <span>优(睡眠7~8小时)</span>
          <span>良(睡眠6~7小时)</span>
          <span>一般(睡眠5~6小时)</span>
          <span>较差(睡眠4~5小时)</span>
          <span>差(睡眠小于4小时)</span>
        </div>
        <Row :gutter="32">
          <Col :md="18">
            <div id="habitsChart" style="width:100%;height:220px;"></div>
          </Col>
          <Col :md="6">
            <div id="habitsCalendarChart" style="width:100%;height:220px;"></div>
          </Col>
        </Row>
      </Card>
      <Spin size="large" fix v-if="isLoading"></Spin>
    </div>

    <Modal v-model="imgmodal.show" title="查看证件" footerHide>
      <img :src="imgmodal.img" style="width:100%;" />
    </Modal>

  </div>
</template>
<style lang="less" src="@/assets/styles/driver/view.less"></style>

<script>
	import {mapState,mapActions} from 'vuex'
  import moment from 'moment'
  import unit   from '@/util/unit'
  import EChart from '@/plugin/EChart'
  import router from '@/router'

  export default {
    data(){
      return {
        driverId:null,
        twelveMonthActive:true,
        searchYear:null,
        data:{},

        dashBoardChart:null,
        driveChart:null,
        driveBehaviorChart:null,
        operBehaviorChart:null,
        moodChart:null,
        moodCalendarChart:null,
        moodSelectedDate:'',
        habitsChart:null,
        habitsCalendarChart:null,
        habitsSelectedDate:'',

        imgmodal:{
          show:false,
          img:''
        },
        yearOption:{
          disabledDate:(d)=>{
            return d > moment().toDate();
          }
        }
      };
    },
    watch:{
      searchYear(v){
        if (v){
          this.twelveMonthActive = false;
          this.update();
        }
      }
    },
    computed:{
      ...mapState('driver/driverView',['isLoading']),
      durationHours(){
        let h = moment.duration(this.data.duration||0,'s').asHours();
        return Math.floor(h);
      }
    },
    methods:{
      moment,time:unit.time,mileage:unit.mileage,
      ...mapActions('driver/driverView',['loadDetail','loadMood','loadHabits']),
      async search(){
        let query = {driverId:this.driverId};
        if (this.searchYear) query.year = moment(this.searchYear).format('YYYY');
        let res = await this.loadDetail(query);
        this.data = res.data;
        this.initData();
      },
      async update(){
        this.moodSelectedDate = '';
        this.habitsSelectedDate = '';
        let query = {driverId:this.driverId};
        if (this.searchYear) query.year = moment(this.searchYear).format('YYYY');
        let res = await this.loadDetail(query);
        this.data = res.data;
        this.updateData();
      },
      twelveMonthClick(){
        this.twelveMonthActive = true;
        this.searchYear = null;
        this.update();
      },
      initData(){
        this.createDashboardChart();
        this.updateData();
      },
      updateData(){
        this.createDriveChart();
        this.createDriveBehaviorChart();
        this.createOperBehaviorChart();
        this.createMoodChart();
        this.createHabitsChart();
      },
      showImage(url){
        this.imgmodal.img = url;
        this.imgmodal.show = true;
      },
      toSta(){
        router.push('/driver/driverStatistics');
      },
      createDashboardChart(){
        let sc = this.data.securityIndex === null ? 100 : this.data.securityIndex;
        this.dashBoardChart = new EChart('dashBoardChart',{
          toolbox:{show:false},
          tooltip:{formatter:"{a} <br/>{b} : {c}"},
          series:[
            {
              name: this.data.driverName,
              type: 'gauge',
              radius:'90%',
              detail: {formatter:'{value}',fontSize:48},
              data: [{value: sc, name: '综合安全指数'}],
              title:{
                fontSize:14,
                offsetCenter:[0,'70%']
              },
              axisLine:{
                lineStyle:{
                  color:[[0.3, '#fd666d'], [0.7, '#37a2da'], [1, '#3be4e4']]
                }
              }
            }
          ]
        });
      },
      createDriveChart(){
        let xAxis = this.data.mileageList.map(o => o.date);
        let mdata = this.data.mileageList.map(o => o.mileage/1000);
        let ddata = this.data.mileageList.map(o => o.duration/60/60);
        let option = {
          title:{show:false},
          toolbox:{show:false},
          color:['#00B050','#FFB163'],
          grid:{x:50,y:40,right:50,bottom:40},
          tooltip: {
            trigger: 'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}`;
              params.forEach(o => {
                let data = o.seriesName.indexOf('里程') >= 0 ? this.mileage(o.data*1000) : this.time(o.data*60,2,2);
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${data}`;
              });
              return tooltiphtml;
            }
          },
          legend: {
            data:['行驶里程','行驶时长'],right:0
          },
          xAxis:[
            {type: 'category',axisLabel:{interval:0,rotate:25},data: xAxis}
          ],
          yAxis:[
            {type:'value',splitNumber:7,min:0,axisPointer:{label:{formatter:'{value}公里'}}},
            {type:'value',splitNumber:7,min:0,axisPointer:{label:{formatter:'{value}小时'}}}
          ],
          series:[
            {name:'行驶里程',type:'bar',barWidth:30,yAxisIndex: 0,data:mdata},
            {name:'行驶时长',type:'line',smooth:true,yAxisIndex: 1,data:ddata}
          ]
        };
        if (this.driveChart){
          this.driveChart.setOption(option);
        } else {
          this.driveChart = new EChart('driveChart',option);
        }
      },
      createDriveBehaviorChart(){
        let xAxis = this.data.badDriveingList.map(o => o.date);
        let overspeedTimes = this.data.badDriveingList.map(o => o.overspeedTimes);// 超速
        let fatigueDrivingTimes = this.data.badDriveingList.map(o => o.fatigueDrivingTimes);// 疲劳驾驶
        let accelerateTimes = this.data.badDriveingList.map(o => o.accelerateTimes);//急加速
        let decelerateTimes = this.data.badDriveingList.map(o => o.decelerateTimes);// 急减速
        let sharpTurnTimes = this.data.badDriveingList.map(o => o.sharpTurnTimes);// 急转弯
        let option = {
          title:{show:false},
          toolbox:{show:false},
          color:['#FFC000','#FF6600','#376092','#9E6A93','#4BACC6'],
          grid:{x:30,y:40,right:0,bottom:40},
          tooltip : {
            trigger:'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}`;
              params.forEach(o => {
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${o.data}次`;
              });
              return tooltiphtml;
            }
          },
          legend: {
            data:['超速','疲劳驾驶','急加速','急减速','急转弯'],right:0
          },
          xAxis:[
            {type:'category',axisLabel:{interval:0},data: xAxis}
          ],
          yAxis:[
            {type:'value',splitNumber:7,min:0},
          ],
          series:[
            {name: '超速',type: 'bar',stack: 'DriveBehavior',barWidth:30,data: overspeedTimes},
            {name: '疲劳驾驶',type: 'bar',stack: 'DriveBehavior',barWidth:30,data: fatigueDrivingTimes},
            {name: '急加速',type: 'bar',stack: 'DriveBehavior',barWidth:30,data: accelerateTimes},
            {name: '急减速',type: 'bar',stack: 'DriveBehavior',barWidth:30,data: decelerateTimes},
            {name: '急转弯',type: 'bar',stack: 'DriveBehavior',barWidth:30,data: sharpTurnTimes},
          ]
        };
        if (this.driveBehaviorChart) {
          this.driveBehaviorChart.setOption(option);
        } else {
          this.driveBehaviorChart = new EChart('driveBehaviorChart',option);
        }
      },
      createOperBehaviorChart(){
        let xAxis = this.data.badOperationList.map(o => o.date);
        let callPhoneTimes = this.data.badOperationList.map(o => o.callPhoneTimes||0);
        let lookPhoneTimes = this.data.badOperationList.map(o => o.lookPhoneTimes||0);
        let option = {
          title:{show:false},
          toolbox:{show:false},
          color:['#31859C','#93CDDD'],
          grid:{x:30,y:40,right:0,bottom:40},
          tooltip : {
            trigger: 'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}`;
              params.forEach(o => {
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${o.data}次`;
              });
              return tooltiphtml;
            }
          },
          legend: {
            data:['行驶中拨打电话','行驶中看手机'],right:0
          },
          xAxis:[
            {type: 'category',axisLabel:{interval:0},data: xAxis}
          ],
          yAxis:[
            {type:'value',splitNumber:7,min:0},
          ],
          series:[
            {name: '行驶中拨打电话',type: 'bar',stack: 'OperBehavior',barWidth:30,data: callPhoneTimes},
            {name: '行驶中看手机',type: 'bar',stack: 'OperBehavior',barWidth:30,data: lookPhoneTimes}
          ]
        };
        if (this.operBehaviorChart){
          this.operBehaviorChart.setOption(option);
        } else {
          this.operBehaviorChart = new EChart('operBehaviorChart',option);
        }
      },
      createMoodChart(){
        let xAxis = this.data.emotionList.map(o => o.date);
        let laugh = this.data.emotionList.map(o => o.laugh);
        let smile = this.data.emotionList.map(o => o.smile);
        let normal = this.data.emotionList.map(o => o.normal);
        let bad = this.data.emotionList.map(o => o.bad);
        let option = {
          title:{show:false},
          toolbox:{show:false},
          color:['#07B254','#7DD354','#FFFF23','#FFBD00'],
          grid:{x:30,y:40,right:0,bottom:40},
          tooltip : {
            trigger: 'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}`;
              params.forEach(o => {
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${o.data}天`;
              });
              return tooltiphtml;
            }
          },
          legend: {
            data:['优','良','一般','差'],right:0
          },
          xAxis:[
            {type: 'category',axisLabel:{interval:0},data: xAxis}
          ],
          yAxis:[
            {type:'value',splitNumber:7,min:0},
          ],
          series:[
            {name: '优',type: 'bar',stack: 'Mood',barWidth:30,data: laugh},
            {name: '良',type: 'bar',stack: 'Mood',barWidth:30,data: smile},
            {name: '一般',type: 'bar',stack: 'Mood',barWidth:30,data: normal},
            {name: '差',type: 'bar',stack: 'Mood',barWidth:30,data: bad}
          ]
        };
        if (this.moodChart){
          this.moodChart.setOption(option);
        } else {
          this.moodChart = new EChart('moodChart',option);
          // 事件
          this.moodChart.chart.on('click',(item) => {
            if (item.name !== this.moodSelectedDate){
              this.moodSelectedDate = item.name;
              this.createMoodCalendarChart();
            }
          });
        }
        // 默认最后月
        this.moodSelectedDate = xAxis[xAxis.length - 1];
        this.moodSelectedDate && this.createMoodCalendarChart();
      },
      async createMoodCalendarChart(){
        let res = await this.loadMood({driverId:this.driverId,date:this.moodSelectedDate});
        let moodData = res.data;
        // 组装日历
        let colors = ['#CCCCCC','#07B254','#7DD354','#FFFF23','#FFBD00'];
        let msd = moment(this.moodSelectedDate,'YYYY-MM');
        let maxDay = msd.daysInMonth();
        let daylist = [];
        let series = [];
        for (let i = 0; i < maxDay; i++){
          let m = moment(this.moodSelectedDate,'YYYY-MM').add(i,'d').format('YYYY-MM-DD');
          let dataitem = moodData.find(o => o.date === m);
          let d = dataitem ? dataitem.sentimentIndex : 0;
          daylist.push([m,'']);
          series.push({value:[m,d],itemStyle:{color:colors[d]}});
        }
        let option = {
          title:{
            text:this.moodSelectedDate,
            x:'center',
            textStyle:{fontSize:16}
          },
          grid:[
            {x:30,y:40,right:0,bottom:40}
          ],
          tooltip: {
            formatter: (params) => {
              let [date,data] = [...params.value];
              let dataText = ['无','优','良','一般','差'][data||0];
              let html = `${date}<br/>
                <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>
                ${params.seriesName}：${dataText}`;
              return html;
            }
          },
          calendar: [{
            left: 'left',top: 60, cellSize: 'auto',
            yearLabel: {show: false},
            orient: 'vertical',
            dayLabel: {firstDay: 1,nameMap: ['周日', '周一', '周二', '周三', '周四', '周五', '周六']},
            monthLabel: {show: false},
            splitLine: {show:false},
            itemStyle: {color:'#E6E5E2',borderColor:'#ffffff'},
            range: this.moodSelectedDate
          }],
          series: [
            {
              type: 'scatter',coordinateSystem: 'calendar',symbolSize: 1,
              label: {
                normal: {
                  show: true,
                  formatter: function (params) {
                    var d = echarts.number.parseDate(params.value[0]);
                    return d.getDate();
                  },
                  textStyle: {
                    color: '#495060'
                  }
                }
              },
              data: daylist
            },
            {name: '情绪',type: 'heatmap',coordinateSystem: 'calendar',data: series},
          ]
        };
        if (this.moodCalendarChart){
          this.moodCalendarChart.setOption(option);
        } else {
          this.moodCalendarChart = new EChart('moodCalendarChart',option);
        }
      },
      createHabitsChart(){
        let xAxis = this.data.habitsList.map(o => o.date);
        let excessive = this.data.habitsList.map(o => o.excessive);
        let excellent = this.data.habitsList.map(o => o.excellent);
        let good = this.data.habitsList.map(o => o.good);
        let commonly = this.data.habitsList.map(o => o.commonly);
        let poor = this.data.habitsList.map(o => o.poor);
        let bad = this.data.habitsList.map(o => o.bad);
        let option = {
          title:{show:false},
          toolbox:{show:false},
          color:['#09585E','#0C8495','#7BD0DC','#D9EFF4','#F0ADA6','#E0635C'],
          grid:{x:30,y:40,right:0,bottom:40},
          tooltip : {
            trigger: 'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}`;
              params.forEach(o => {
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${o.data}天`;
              });
              return tooltiphtml;
            }
          },
          legend: {
            data:['过度','优','良','一般','较差','差'],right:0
          },
          xAxis:[
            {type: 'category',axisLabel:{interval:0},data: xAxis}
          ],
          yAxis:[
            {type:'value',splitNumber:7,min:0},
          ],
          series:[
            {name: '过度',type: 'bar',stack: 'Mood',barWidth:30,data: excessive},
            {name: '优',type: 'bar',stack: 'Mood',barWidth:30,data: excellent},
            {name: '良',type: 'bar',stack: 'Mood',barWidth:30,data: good},
            {name: '一般',type: 'bar',stack: 'Mood',barWidth:30,data: commonly},
            {name: '较差',type: 'bar',stack: 'Mood',barWidth:30,data: poor},
            {name: '差',type: 'bar',stack: 'Mood',barWidth:30,data: bad}
          ]
        };
        if (this.habitsChart){
          this.habitsChart.setOption(option);
        } else {
          this.habitsChart = new EChart('habitsChart',option);
          this.habitsChart.chart.on('click',(item) => {
            if (item.name !== this.habitsSelectedDate){
              this.habitsSelectedDate = item.name;
              this.createHabitsCalendarChart();
            }
          });
        }
        // 默认最后月
        this.habitsSelectedDate = xAxis[xAxis.length - 1];
        this.habitsSelectedDate && this.createHabitsCalendarChart();
      },
      async createHabitsCalendarChart(){
        let res = await this.loadHabits({driverId:this.driverId,date:this.habitsSelectedDate});
        let habitsData = res.data;
        // 组装日历
        let colors = ['#CCCCCC','#E0635C','#F0ADA6','#D9EFF4','#7BD0DC','#0C8495','#09585E'];
        let hsd = moment(this.habitsSelectedDate);
        let maxDay = hsd.daysInMonth();
        let daylist = [];
        let series = [];
        for (let i = 0; i < maxDay; i++){
          let m = moment(this.habitsSelectedDate).add(i,'d').format('YYYY-MM-DD');
          let dataitem = habitsData.find(o => o.date === m);
          let d = dataitem ? dataitem.sleepLevel||0 : 0;
          daylist.push([m,'']);
          series.push({value:[m,d],itemStyle:{color:colors[d]}});
        }
        let option = {
          title:{
            text:moment(this.habitsSelectedDate).format('YYYY年M月'),
            x:'center',
            textStyle:{fontSize:16}
          },
          grid:[
            {x:30,y:40,right:0,bottom:40}
          ],
          tooltip: {
            formatter: (params) => {
              let [date,data] = [...params.value];
              let dataText = ['无','差','较差','一般','良','优','过度'][data||0];
              let html = `${date}<br/>
                <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>
                ${params.seriesName}：${dataText}`;
              return html;
            }
          },
          calendar: [{
            left: 'left',top: 60, cellSize: 'auto',
            yearLabel: {show: false},
            orient: 'vertical',
            dayLabel: {firstDay: 1,nameMap: ['周日', '周一', '周二', '周三', '周四', '周五', '周六']},
            monthLabel: {show: false},
            splitLine: {show:false},
            itemStyle: {color:'#E6E5E2',borderColor:'#ffffff'},
            range: moment(this.habitsSelectedDate).format('YYYY-MM')
          }],
          series: [
            {
              type: 'scatter',
              coordinateSystem: 'calendar',
              symbolSize: 1,
              label: {
                normal: {
                  show: true,
                  formatter: function (params) {
                    var d = echarts.number.parseDate(params.value[0]);
                    return d.getDate();
                  },
                  textStyle: {
                    color: '#ffffff'
                  }
                }
              },
              data: daylist
            },
            {
              name: '生活习惯',
              type: 'heatmap',
              coordinateSystem: 'calendar',
              data: series
            },
          ]
        };

        if (this.habitsCalendarChart){
          this.habitsCalendarChart.setOption(option);
        } else {
          this.habitsCalendarChart = new EChart('habitsCalendarChart',option);
        }
      }
    },
    filters:{
      isNull(v){
        return v === null ? '-' : v;
      }
    },
    mounted(){
      let p = this.$route.query;
      if (p.id) {
        this.driverId = p.id;
        this.$refs.driverComplete.setOptions({value:p.id,label:p.name,tel:p.tel});
        this.search();
      }
    },
    destroyed(){
      this.dashBoardChart && this.dashBoardChart.dispose();
      this.driveChart && this.driveChart.dispose();
      this.driveBehaviorChart && this.driveBehaviorChart.dispose();
      this.operBehaviorChart && this.operBehaviorChart.dispose();
      this.moodChart && this.moodChart.dispose();
      this.moodCalendarChart && this.moodCalendarChart.dispose();
      this.habitsChart && this.habitsChart.dispose();
      this.habitsCalendarChart && this.habitsCalendarChart.dispose();
    }
  }
</script>
